<template>
  <div class="department-manage">
    <el-card>
      <div class="header-title">部门管理</div>
      <el-form :inline="true" :model="search" style="margin-bottom: 16px;">
        <el-form-item label="部门名称">
          <el-input v-model="search.deptName" placeholder="部门名称" />
        </el-form-item>
        <el-form-item label="启用状态">
          <el-select v-model="search.status" placeholder="启用状态" style="width: 120px;">
            <el-option label="全部" value="" />
            <el-option label="已启用" value="1" />
            <el-option label="已停用" value="0" />
          </el-select>
        </el-form-item>
        <el-button type="primary" @click="fetchData">查询</el-button>
        <el-button @click="reset">重置</el-button>
        <el-button type="success" @click="openAdd">新增部门</el-button>
      </el-form>
      <el-table :data="tableData" border>
        <el-table-column prop="departmentName" label="部门名称" />
        <el-table-column prop="departmentHead" label="部门负责人 " />
        <el-table-column label="人员明细">
          <template #default="scope">
            <el-link type="primary" @click="openUserDialog(scope.row)">查看</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="启用状态">
          <template #default="scope">
            <span :style="{ color: scope.row.status === 1 ? '#13ce66' : '#ff4949', 'margin-right': '8px' }">
              {{ scope.row.status === 1 ? '已启用' : '已停用' }}
            </span>
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              :active-color="'#13ce66'"
              :inactive-color="'#ff4949'"
              @change="val => handleStatusChange(scope.row, val)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" type="primary" @click="openEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 16px;"
        background
        layout="prev, pager, next, jumper, ->, total"
        :current-page="pagination.page"
        :page-size="pagination.size"
        :total="pagination.total"
        @current-change="handlePageChange"
      />
      <el-dialog v-model="dialogVisible" :title="dialogTitle" width="400px">
        <el-form :model="form" label-width="80px">
          <el-form-item label="部门名称">
            <el-input v-model="form.deptName" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </template>
      </el-dialog>
      <el-dialog v-model="userDialogVisible" title="人员明细" width="800px">
        <el-table :data="userList">
          <el-table-column prop="username" label="账号名称" />
          <el-table-column prop="realName" label="姓名" />
          <el-table-column prop="phone" label="手机号" />
          <el-table-column prop="departmentName" label="归属部门" />
          <el-table-column prop="roleName" label="角色名称" />
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <span :style="{color: scope.row.status === 1 ? '#13ce66' : '#ff4949'}">
                {{ scope.row.status === 1 ? '已启用' : '已停用' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" />
        </el-table>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getDepartmentPage, addDepartment, updateDepartment, deleteDepartment, updateDepartmentStatus, getUsersByDepartment } from '@/api/department'
import { ElMessageBox, ElMessage } from 'element-plus'

const search = ref({ deptName: '', status: '' })
const tableData = ref([])
const pagination = ref({ page: 1, size: 10, total: 0 })
const dialogVisible = ref(false)
const dialogTitle = ref('新增部门')
const form = ref({ id: null, deptName: '', status: 1 })
const userDialogVisible = ref(false)
const userList = ref([])

onMounted(() => { fetchData() })

function fetchData() {
  getDepartmentPage({
    deptName: search.value.deptName,
    status: search.value.status,
    page: pagination.value.page,
    size: pagination.value.size
  }).then(res => {
    if (res.code === 200) {
      tableData.value = res.data.records || []
      pagination.value.total = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取数据失败')
    }
  })
}

function reset() {
  search.value = { deptName: '', status: '' }
  pagination.value.page = 1
  fetchData()
}

function openAdd() {
  dialogTitle.value = '新增部门'
  form.value = { id: null, deptName: '', status: 1 }
  dialogVisible.value = true
}

function openEdit(row: any) {
  dialogTitle.value = '编辑部门'
  form.value = { ...row }
  dialogVisible.value = true
}

function submitForm() {
  const api = form.value.id ? updateDepartment : addDepartment
  api(form.value).then(res => {
    if (res.code === 200) {
      dialogVisible.value = false
      fetchData()
      ElMessage.success('操作成功')
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  })
}

function handlePageChange(page: number) {
  pagination.value.page = page
  fetchData()
}

function handleDelete(row: any) {
  ElMessageBox.confirm('确定要删除该部门吗？', '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(() => {
    deleteDepartment(row.id).then(res => {
      if (res.code === 200) {
        ElMessage.success('删除成功')
        fetchData()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    })
  })
}

function handleStatusChange(row: any, val: number) {
  updateDepartmentStatus(row.id, val).then(res => {
    if (res.code === 200) {
      ElMessage.success('状态已更新')
    } else {
      ElMessage.error('状态更新失败')
      row.status = val === 1 ? 0 : 1
    }
  })
}

function openUserDialog(row: any) {
  getUsersByDepartment(row.id).then(res => {
    if (res.code === 200) {
      userList.value = res.data || []
      userDialogVisible.value = true
    } else {
      ElMessage.error(res.message || '获取用户列表失败')
    }
  })
}
</script>

<style scoped>
.header-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 16px;
}
.department-manage {
  padding: 24px;
}
</style>
